package com.mlk.busPram.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mlk.busPram.mapper.EngBusParamMapper;
import com.mlk.busPram.po.EngBusParam;
import com.mlk.busPram.service.BusParamService;
import com.mlk.busPram.vo.EngBusParamVO;
import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.exception.GlobalException;
import com.mlk.core.util.ServerResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class BusParamServiceImpl implements BusParamService {

    @Resource
    private EngBusParamMapper engBusParamMapper;

    /**
     * 分页数据展示
     *
     * @param vo
     * @return
     */
    @Override
    @Page
    public Pager busParamListPage(EngBusParamVO vo) {
        return Pager.adapt(this.engBusParamMapper.selectForPage(vo));
    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @Override
    @Transactional
    public ServerResponse add(EngBusParam param) {
        // 首先判断下,是否存在相同的
        int count = this.engBusParamMapper.selectCount(new EntityWrapper<>(EngBusParam.builder().type(param.getType()).name(param.getName()).build()));
        if(count != 0){
            throw new GlobalException("该名称已存在");
        }
        count = this.engBusParamMapper.insert(param);
        if (count == 0) {
            throw new GlobalException("添加失败");
        }

        return ServerResponse.ok("添加成功");
    }

    /**
     * 删除Ent
     *
     * @param id
     * @return
     */
    @Override
    public ServerResponse del(Integer id) {
        int count = this.engBusParamMapper.deleteById(id);
        if (count == 0) {
            throw new GlobalException("删除失败");
        }

        return ServerResponse.ok("删除成功");
    }

    /**
     * 更新
     *
     * @param param
     * @return
     */
    @Override
    public ServerResponse update(EngBusParam param) {
        int count = this.engBusParamMapper.updateById(param);

        if (count == 0) {
            throw new GlobalException("更新失败");
        }

        return ServerResponse.ok("更新成功");
    }

    /**
     * 查询参数信息
     *
     * @param typeId
     * @return
     */
    @Override
    public ServerResponse queryParam(Integer typeId) {
        EngBusParamVO vo = new EngBusParamVO();
        vo.setType(typeId);
        return ServerResponse.ok(this.busParamListPage(vo));
    }
}
